package client;
import java.awt.Color;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.BorderFactory;
import javax.swing.JPanel;


public class ClientMain {
	
	//Connection settings
	public static String hostName = "localhost";
	public static boolean launchHost = true;
	public static boolean launchNonHost = true;
	
	public static void main(String args[]) {
		Thread p1 = new Thread(new Runnable() { 
			public void run() {
				new GameFrame().init(true);
			}
		});
		Thread p2 = new Thread(new Runnable() { 
			public void run() {
				new GameFrame().init(false);
			}
		});
		if(launchHost) 
			p1.start();
		if(launchHost&&launchNonHost) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		if(launchNonHost)
			p2.start();
	}
	
	public static JPanel setup(boolean host) {

		//setup socket
		Socket socket = null;
		PrintWriter out = null;
		BufferedReader in = null;
		int playerID = host?0:1;
		try {
			if(host) {
				ServerSocket serverSocket = new ServerSocket(5555);
				socket = serverSocket.accept();
				System.out.println("Host connected!");
			}
			else {
				socket = new Socket(hostName, 5555);			
			}
			out = new PrintWriter(socket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
		//setup protocol
		ClientProtocol protocol = new ClientProtocol(playerID, out, in);
		
		//setup model
		ClientModel model = new ClientModel(playerID);
		
		//setup view
		GameView view = new GameView(model);
		JPanel gamePanel = new JPanel();
		gamePanel.add(view);
		gamePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
		
		//setup controller
		new GameController(view, model, protocol);
		
		
		return gamePanel;
	}
}
